package util;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;

public class FileUtil {

    public static final int PAGE_SIZE = 1024*1024; //1M

    public static final String DEFAULT_CHARSET = "utf-8";

    // 读取文件内容到字符串的方法
    public static String readFileToString(String filePath,String charset) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)),charset);
    }

    public static String readFileString(String filePath, Charset charset) throws IOException {
        return Files.readString(Paths.get(filePath),charset);
    }

    public static String readFileString(String filePath) throws IOException {
        // java 11 开始提供的方法，读取文件不能超过2G，与你的内存息息相关
        return Files.readString(Paths.get(filePath));
    }

    public static String readFileByChars(String fileName)
    {
        File file = new File(fileName);
        Reader reader = null;
        StringBuilder Content= new StringBuilder();
        try
        {
            // 一次读多个字节
            char[] buff = new char[PAGE_SIZE];
            int charRead;
            reader = new InputStreamReader(new FileInputStream(file));
            // 读入多个字符到字符数组中，charRead为一次读取字符数
            while ((charRead = reader.read(buff)) >0)
            {
                Content.append(buff,0,charRead);
            }
        }
        catch (Exception e1)
        {
            e1.printStackTrace();
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e1)
                {
                    System.out.println("readFileByBytes() Exception:" + e1.getMessage());
                }
            }
        }

        return Content.toString();
    }

    //读取二进制文件
    /**
     * 以字节为单位读取文件，常用于读二进制文件，如图片、声音、影像等文件。
     */
    public static byte[] readFileByBytes(String fileName) {
        InputStream in = null;
        //BufferedInputStream in= null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            in = new FileInputStream(fileName);
            //in = new BufferedInputStream(new FileInputStream(filename));
            byte[] buf = new byte[PAGE_SIZE];
            int length;
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return out.toByteArray();
    }

    /**
     * 随机读取文件内容
     */
    public static byte[] readFileByRandomAccess(String fileName,long beginIndex,int targetLen) {
        RandomAccessFile randomFile = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            // 打开一个随机访问文件流，按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            //int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread,total=0;
            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                if (targetLen > 0 && targetLen < total + byteread)
                {
                    byteread = targetLen - total;
                    total += byteread;
                    out.write(bytes, 0, byteread);
                    break;
                }
                else
                {
                    total += byteread;
                    out.write(bytes, 0, byteread);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }

        return out.toByteArray();
    }

    public static ByteBuffer readRandomFile(String fileName,long offset,int targetLen){
        ByteBuffer buffer = ByteBuffer.allocate(targetLen);
        RandomAccessFile randomAccessFile;
        try {
            randomAccessFile = new RandomAccessFile(fileName, "r");  //只读模式
            randomAccessFile.seek(offset);
            int byteread,total=0;
            // 将一次读取的字节数赋给byteread
            byte[] bytes=new byte[PAGE_SIZE];
            while ((byteread = randomAccessFile.read(bytes)) != -1) {
                if (targetLen > 0 && targetLen < total + byteread)
                {
                    byteread = targetLen - total;
                    total += byteread;
                    buffer.put(bytes,0, byteread);
                    break;
                }
                else
                {
                    total += byteread;
                    buffer.put(bytes,0, byteread);
                }
            }
            randomAccessFile.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        // 转成可读状态
        buffer.flip();

        return buffer;
    }

    public  static boolean removeFile(String fileName){
        File file=new File(fileName);
        return  file.delete();
    }
    public static int writeFileByRandomAccess(String fileName,long beginIndex,byte[] bytes,int len) {
        RandomAccessFile randomFile = null;
        try {
            // 打开一个随机访问文件流
            randomFile = new RandomAccessFile(fileName, "rw");
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            randomFile.write(bytes,0,len);
        }catch (IOException e) {
            e.printStackTrace();
            return  -1;
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                    return len;
                }
            }
        }

        return len;
    }

    public static long StreamToStream(InputStream in, OutputStream out)
            throws IOException {
        byte[] buff = new byte[PAGE_SIZE];
        int read;
        long totalWrite = 0;
        while ((read = in.read(buff)) > 0) {
            totalWrite += read;
            out.write(buff, 0, read);
            out.flush();
        }
        out.flush();
        return totalWrite;
    }

    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为:" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getFileExtension(String fileName)
    {
       return fileName.lastIndexOf(".")==-1?"":fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String getHex(byte[] source) {
        final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        char[] out = new char[source.length * 2];
        for (int i = 0; i < source.length; i ++) {
            out[i * 2] = hexDigits[source[i] >>> 4 & 0xf];
            out[i * 2 + 1] = hexDigits[source[i] & 0xf];
        }
        return new String(out);
    }

    public static String getSHA1(String data) {
        if (data == null) {
            return null;
        }
        try {
            MessageDigest md = java.security.MessageDigest.getInstance("SHA1");
            md.update(data.getBytes());
            byte[] tmp = md.digest();
            return getHex(tmp);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String getMD5(String data) {
        try {
            MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(data.getBytes());
            byte[] tmp = md.digest();
            return getHex(tmp);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String GetCurPath()
    {
        File directory = new File("");//设定为当前文件夹
        String filePath=directory.getAbsolutePath();
        if (!filePath.substring(filePath.length() - 1).equals(File.separator)) filePath += File.separator;
        return filePath;
    }

}
